using AutoMapper;
using BackData;
using Domain;
using Domain.DTOs.ProcessSteps;
using Domain.工艺工序;
using Infratructure;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Transactions;
using Team.API.Applocation.Command.Makesteps;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Hanldler.Makesteps
{
    /// <summary>
    /// 新增成品工艺工序处理器：负责生产工艺节点的创建及操作日志记录
    /// </summary>
    public class CreateMakestepHandler : IRequestHandler<CreateMakestepCommand, APIResult<MakestepListDTO>>
    {
        private readonly IMapper mapper;
        private readonly IRepository<Makestepmodel> repository;
        private readonly IRepository<Nlogmodel> logRepository;
        private readonly ILogger<CreateMakestepHandler> logger;

        public CreateMakestepHandler(
            IMapper mapper,
            IRepository<Makestepmodel> repository,
            IRepository<Nlogmodel> logRepository,
            ILogger<CreateMakestepHandler> logger)
        {
            this.mapper = mapper;
            this.repository = repository;
            this.logRepository = logRepository;
            this.logger = logger;
        }

        public async Task<APIResult<MakestepListDTO>> Handle(CreateMakestepCommand request, CancellationToken cancellationToken)
        {
            var currentUser = string.IsNullOrWhiteSpace(request.CurrentUserName) ? "系统" : request.CurrentUserName;

            var entity = mapper.Map<Makestepmodel>(request);
            entity.Id = YitIdHelper.NextId();
            entity.Parentid = 0;
            entity.IsDel = false;

            var logEntity = new Nlogmodel
            {
                Id = YitIdHelper.NextId(),
                Message = $"{currentUser}新增成品工艺工序：{entity.Processname}",
                Category = "Process",
                Otherkey = entity.Id,
                Operatingtime = DateTime.Now,
                Operator = currentUser,
                IsDel = false
            };

            // 使用事务确保“业务数据+日志”要么同时成功、要么同时失败
            using var transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled);
            try
            {
                var effect = await repository.AddAsync(entity);
                if (effect <= 0)
                {
                    logger.LogWarning("[工艺工序-新增] 保存失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<MakestepListDTO>.Faile("新增工艺工序失败");
                }

                var logEffect = await logRepository.AddAsync(logEntity);
                if (logEffect <= 0)
                {
                    logger.LogWarning("[工艺工序-新增] 日志写入失败，操作人：{User}，工序：{Process}", currentUser, entity.Processname);
                    return APIResult<MakestepListDTO>.Faile("新增工艺工序失败：日志写入失败");
                }

                transaction.Complete();
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "[工艺工序-新增] 事务执行异常，操作人：{User}", currentUser);
                throw;
            }

            var dto = mapper.Map<MakestepListDTO>(entity);
            return APIResult<MakestepListDTO>.Ok("新增工艺工序成功", dto);
        }
    }
}

